/**
 * Copyright (c) Islon Scherer 2010.
 */

package progma.lang.compiler;

import java.io.FileInputStream;
import java.util.HashMap;

import org.antlr.runtime.ANTLRInputStream;
import org.antlr.runtime.CommonTokenStream;
import org.antlr.runtime.Token;
import org.antlr.runtime.tree.CommonTree;
import org.antlr.runtime.tree.CommonTreeNodeStream;

import progma.lang.compiler.exception.ProgmaSyntaxException;

public class Compiler {
	
	private boolean printTokens = false;

	public HashMap<String, byte[]> compile(String file) throws Exception {
		ANTLRInputStream input = new ANTLRInputStream(new FileInputStream(file));
		ProgmaLexer lexer = new ProgmaLexer(input);
		CommonTokenStream tokens = new CommonTokenStream(lexer);
		if(printTokens) {
			for(Object t : tokens.getTokens()) {
				Token to = (Token) t;
				System.out.println(to);
			}
		}
		ProgmaParser parser = new ProgmaParser(tokens);
		CommonTree t = (CommonTree) parser.program().getTree();
		int errors = parser.getNumberOfSyntaxErrors();
		if(errors > 0)
			throw new ProgmaSyntaxException(errors);
		
		CommonTreeNodeStream nodes = new CommonTreeNodeStream(t);
		nodes.setTokenStream(tokens);
		ProgmaTreeParser treeParser = new ProgmaTreeParser(nodes);
		treeParser.setSymbolTable(parser.getSymbolTable());
		treeParser.program();
		BytecodeGenerator bg = treeParser.getGenerator();
		return bg.getClasses();
	}
}
